import { readFile, writeFile } from 'fs/promises';

export async function imageToBase64(filePath) {
  try {
    const data = await readFile(filePath);
    const mimeType = getMimeType(filePath);
    return `data:${mimeType};base64,${data.toString('base64')}`;
  } catch (error) {
    console.error('Error converting image to base64:', error);
    throw error;
  }
}

export async function base64ToImage(base64String, outputPath) {
  try {
    if (!/^data:image\/[a-z]+;base64,/.test(base64String)) {
      throw new Error('Invalid base64 image format');
    }
    
    const base64Data = base64String.replace(/^data:image\/\w+;base64/, '')
    const buffer = Buffer.from(base64Data, 'base64');
    await writeFile(outputPath, buffer);
    return outputPath;
  } catch (error) {
    console.error('Error converting base64 to image:', error);
    throw error;
  }
}

function getMimeType(filePath) {
  const extension = filePath.split('.').pop().toLowerCase();
  switch(extension) {
    case 'png': return 'image/png';
    case 'jpg':
    case 'jpeg': return 'image/jpeg';
    case 'gif': return 'image/gif';
    case 'webp': return 'image/webp';
    default: return 'application/octet-stream';
  }
}

export default {
  imageToBase64,
  base64ToImage,
}